using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Windows.Input;
using Microsoft.Practices.Prism.Commands;
using TrackMe.Dto;

namespace TrackMe.Apps.VM
{
	[Export]
	public class CreateVM : BasicViewModel<ICreateView>
	{
		private readonly IDatabase database;
		public ICommand AddProjectCmd { get; private set; }
		public ICommand AddTaskCmd { get; private set; }
		#pragma warning disable 0649
		[Import]
        private CompositionContainer container;
        [Import]
        private IDialogService dialogService;
		#pragma warning restore 0649

		[ImportingConstructor]
		public CreateVM(ICreateView view, IDatabase database): base(view)
		{
			this.database = database;
            AddProjectCmd = new DelegateCommand<ITaskForSelect>(OnCreateProject);
            AddTaskCmd = new DelegateCommand<ITaskForSelect>(OnCreateTask);
			LoadProjects();
		}

		private void OnCreateProject(ITaskForSelect taskForSelect)
        {
            var vm = container.GetExportedValue<ProjectEditVM>();
            vm.Model = AutoIntf.New<IEditProject>();
            if (dialogService.PopupDialog(vm))
                ProjectsChanged(vm.Model.Id);
        }

        private void OnCreateTask(ITaskForSelect taskForSelect)
        {
            var vm = container.GetExportedValue<TaskEditVM>();
            vm.Model = AutoIntf.New<IEditTask>();
            vm.Model.ProjectId = SelectedProject.Id;
            if (dialogService.PopupDialog(vm))
                TasksChanged(vm.Model.Id);
        }
        
        private void LoadProjects()
		{
			Projects = database.ProjectList();
			RaisePropertyChanged(() => Projects);
		}
		public IList<IProjectForList> Projects { get; private set; }
        public IList<ITaskForList> Tasks { get; private set; }

		// View side
        private IProjectForList selectedProject;
	    public IProjectForList SelectedProject
	    {
	        get { return selectedProject; }
	        set 
            {
                if (selectedProject != value)
                {
                    selectedProject = value;
                    LoadTasks();
                }
            }
	    }

	    private void LoadTasks()
	    {
	        Tasks = database.ProjectTask(selectedProject.Id);
            RaisePropertyChanged(() => Tasks);
        }

	    public void ProjectsChanged(int focusOnId)
		{
			LoadProjects();
			SelectedProject = Projects.First(p => p.Id == focusOnId);
			RaisePropertyChanged(() => SelectedProject);
		}

	    public void TasksChanged(int id)
	    {
	        LoadTasks();
	        SelectedTask = Tasks.First(t => t.Id == id);
            RaisePropertyChanged(() => SelectedTask);
	    }

	    public ITaskForList SelectedTask { get; set; }
	}
}

